package com.blog.vueblogx.config.shiro;

import com.blog.vueblogx.entity.User;
import com.blog.vueblogx.service.UserService;
import com.blog.vueblogx.util.JwtUtils;
import io.jsonwebtoken.Jwt;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @version 1.0
 * @Author: 许啸林
 * @Date: 2022/2/14 13:57
 */
@Component
public class AccountRealm extends AuthorizingRealm {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken ;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
         JwtToken jwtToken = (JwtToken) token;
         String userId = jwtUtils.getClaimByToken(jwtToken.getPrincipal().toString()).getSubject();
         User user = userService.getById(Integer.valueOf(userId));
         if(user == null) {
             throw new UnknownAccountException("账户不存在");
         }
         if(user.getStatus() == -1) {
             throw new LockedAccountException("账户被锁定");
         }
        AccountProfile profile = new AccountProfile();
        BeanUtils.copyProperties(user,profile);
        return new SimpleAuthenticationInfo(profile, jwtToken.getCredentials(), getName());
    }
}
